<template>
   <view>
      <uv-picker
         ref="picker"
         :columns="addressList"
         :loading="loading"
         keyName="name"
         @change="change"
         @confirm="confirm"
      ></uv-picker>
   </view>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue';
import regionsData from '@/static/regions.json';

const picker = ref();
const loading = ref(true);
const provinces = ref([]);
const citys = ref([]);
const areas = ref([]);
const pickerValue = ref([0, 0, 0]);
const defaultValue = ref([3442, 1, 2]);
const prevIndex = ref(0);

const addressList = computed(() => {
   return [provinces.value, citys.value, areas.value];
});

const loadData = () => {
   try {
      provinces.value = regionsData.sort((a: any, b: any) =>
         Number(a.code) > Number(b.code) ? 1 : -1
      );
      handlePickValueDefault();
      uni.$uv.sleep(200).then(() => {
         loading.value = false;
      });
   } catch (err) {
      console.error('省份数据加载失败:', err);
      loading.value = false;
   }
};

const handlePickValueDefault = () => {
   pickerValue.value[0] = provinces.value.findIndex(
      item => Number(item.id) === defaultValue.value[0]
   );
   citys.value = provinces.value[pickerValue.value[0]]?.children || [];
   pickerValue.value[1] = citys.value.findIndex(item => Number(item.id) === defaultValue.value[1]);
   areas.value = citys.value[pickerValue.value[1]]?.children || [];
   pickerValue.value[2] = areas.value.findIndex(item => Number(item.id) === defaultValue.value[2]);
   picker.value.setIndexs([pickerValue.value[0], pickerValue.value[1], pickerValue.value[2]]);
};

const change = (e: any) => {
   if (loading.value) return;

   const { columnIndex, index } = e;
   if (columnIndex === 0) {
      prevIndex.value = index;
      citys.value = provinces.value[index]?.children || [];
      areas.value = citys.value[0]?.children || [];
      picker.value.setIndexs([prevIndex.value, index, 0]);
   } else if (columnIndex === 1) {
      areas.value = citys.value[index]?.children || [];
      picker.value.setIndexs([prevIndex.value, index, 0]);
   }
};
const open = () => {
   picker.value.open();
   handlePickValueDefault();
};
const confirm = (e: any) => {
   console.log('确认选择的地区', e);
};

onMounted(() => {
   loadData();
});

defineExpose({
   open,
});
</script>

<style lang="scss" scoped></style>
